<% String path=request.getContextPath(); String basePath=request.getScheme() + "://" + request.getServerName() + ":" +
    request.getServerPort() + path + "/" ; %>
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
        <!DOCTYPE html>
        <html>

        <head>
            <base href="<%=basePath%>">
            <title>变更申请</title>

        </head>
        <style>
            .tdText {
                text-align: right;
                width: 400px;
                height: 20px;
            }

            input:disabled {
                background-color: #dae1ed;
            }
        </style>

        <body>
            <%@ include file="/WEB-INF/jsp/common/header.jsp" %>
                <%@ include file="/WEB-INF/jsp/common/loadDiv.jsp" %>

                    <script type="text/javascript">
                        $(function () {
                            /**
                             * 初始化日期选择框
                             */
                            $('#startTime').datebox('setValue', getBeforeCurrentDate90Days());
                            $('#endTime').datebox('setValue', getNowFormatDate());
                            $('#startInquiryResultTime').datebox('setValue', getBeforeCurrentDate90Days());
                            $('#endInquiryResultTime').datebox('setValue', getNowFormatDate());
                            // 初始化列表
                            bingGrid();
                            // 初始化询价结果的datagrid
                            setInquiriesDataGrid();
                            $("#uploadbtn").bind("click", function (e) {
                                $("#uploadpicker").click();
                            });
                        });

                    </script>

                    <div class="query_criteria" id="query_criteria">
                        <div style="margin: 5px 0px">
                            <label style="font-size: 12px;">创建时间：</label> <input class="easyui-datebox" name="startTime"
                                id="startTime"
                                data-options="required:true,showSeconds:false,formatter:myformatter,parser:myparser"
                                value="" style="width: 150px"> <label style="font-size: 10px;">~</label> <input
                                class="easyui-datebox" name="endTime" id="endTime"
                                data-options="required:true,showSeconds:false,formatter:myformatter,parser:myparser"
                                style="width: 150px" /> <label style="margin-left: 20px; font-size: 12px;">状态：</label>
                            <input class="easyui-combobox" id="status" name="status" style="width: 80px;" data-options="valueField: 'value',editable:false,
		textField: 'label',panelHeight:'auto',data: [{
			label: '全部',
			value: ''
		},{
			label: '待提交',
			value: '0',
			'selected':true
		},{
			label: '已提交',
			value: '1'
		},{
			label: '已完成',
			value: '2'
		}]">
                            <a id="search" href="javascript:void(0)" class="easyui-linkbutton"
                                data-options="iconCls:'icon-search'" onclick="searchOederList()">查询</a>
                            <a id="export" href="javascript:void(0)" class="easyui-linkbutton"
                                data-options="iconCls:'icon-export'" onclick="exportOrderList()">导出</a>
                        </div>
                        <table id="initTable"></table>
                        <%-- 编辑、详情窗口 --%>
                            <div id="edit" class="easyui-window" closed="true" modal="true" title="采购订单"
                                style="width: 930px; height: 400px; padding: 5px 5px; top: 50px;">
                                <div id="tabs" class="easyui-tabs" style="width: 885px; height: 350px">
                                    <div title="基本信息" style="padding: 5px;">
                                        <form id="frmOrder">
                                            <table>
                                                <tr style="margin-bottom: 10px">
                                                    <td colspan="1" class="tdText"><input type="hidden"
                                                            id="ordId" /><input type="hidden" id="resId" />
                                                        <input type="hidden" id="infId" /><label
                                                            style="width: 40%; text-align: right;">订单编号：</label> <input
                                                            id="ordCode" class="easyui-textbox" style="width: 60%"
                                                            data-options="disabled:true">
                                                    </td>
                                                    <td colspan="1" class="tdText"><label
                                                            style="width: 40%; text-align: right;">订单名称：</label> <input
                                                            id="ordName" data-options="required:true"
                                                            class="easyui-textbox" style="width: 60%"></td>
                                                    <td colspan="1" class="tdText"><label
                                                            style="width: 40%; text-align: right;">合同金额：</label>
                                                        <input id="ordFreight" class="easyui-textbox"
                                                            data-options="disabled:true" style="width: 60%">
                                                    </td>
                                                </tr>
                                                <tr style="margin-bottom: 10px">
                                                    <td colspan="1" class="tdText"><label
                                                            style="width: 40%; text-align: right;">供应商编码：</label>
                                                        <input id="infCode" class="easyui-textbox"
                                                            data-options="disabled:true" style="width: 60%">
                                                    </td>
                                                    <td colspan="1" class="tdText"><label
                                                            style="width: 40%; text-align: right;">供应商名称：</label>
                                                        <input id="infName" class="easyui-textbox"
                                                            data-options="disabled:true" style="width: 60%">
                                                    </td>
                                                </tr>
                                                <tr style="margin-bottom: 10px">

                                                    <td colspan="1" class="tdText"><label
                                                            style="width: 40%; text-align: right;">签订地点：</label> <input
                                                            id="ordSignAddress" class="easyui-textbox"
                                                            style="width: 60%">
                                                    </td>
                                                    <td colspan="1" class="tdText"><label
                                                            style="width: 40%; text-align: right;">签订日期：</label> <input
                                                            id="ordSignDate" class="easyui-datebox" style="width: 60%">
                                                    </td>
                                                    <!-- <td colspan="1" class="tdText"><label
                                                            style="width: 40%; text-align: right;">生效日期：</label> <input
                                                            id="ordResultDate" class="easyui-datebox"
                                                            style="width: 60%">
                                                    </td> -->
                                                </tr>
                                                <tr style="margin-bottom: 10px">

                                                    <td colspan="1" class="tdText"><label
                                                            style="width: 40%; text-align: right;">是否框架：</label>
                                                        <input id="ordIsSign" class="easyui-combobox" style="width: 60%"
                                                            data-options="required:true,valueField: 'value',editable:false,
		textField: 'label',panelHeight:'auto',data: [{
			label: '否',
			value: '0'
		}]">
                                                    </td>
                                                    <!-- <td colspan="1" class="tdText"><input type="hidden"
                                                            id="ordContractId"> <label
                                                            style="width: 60%; text-align: right;">合同执行人：</label> <input
                                                            id="ordContractName" class="easyui-textbox"
                                                            style="width: 40%" data-options="disabled:true">
                                                    </td> -->

                                                    <td colspan="1" class="tdText"><label
                                                            style="width: 40%; text-align: right;">是否推送OA：</label>
                                                        <input id="ordContractType" class="easyui-combobox"
                                                            style="width: 60%" data-options="required:true,valueField: 'value',editable:false,
		textField: 'label',panelHeight:'auto',data: [{
			label: '是',
			value: '1'
		},{
			label: '否',
			value: '0'
		}]">
                                                    </td>
                                                </tr>
                                                <tr>
                                                    <td colspan="1" class="tdText">
                                                        <label style="width:40%;text-align:right;">是否自提：</label>
                                                        <input class="easyui-combobox" id="inqIsOwn" name="inqIsOwn"
                                                            style="width: 60%;" data-options="required:true,valueField: 'value',editable:false,
            textField: 'label',panelHeight:'auto',data: [{
                label: '供应商送货',
                value: '2'
            },{
                label: '自提',
                value: '1'
            }]">
                                                    </td>
                                                    <td colspan="1" class="tdText">
                                                        <label style="width:40%;text-align:right;">是否过磅 ：</label>
                                                        <input class="easyui-combobox" id="inqIsWeight"
                                                            name="inqIsWeight" style="width: 60%;" data-options="required:true,valueField: 'value',editable:false,
                textField: 'label',panelHeight:'auto',data: [{
                    label: '无需过磅',
                    value: '1'
                },{
                    label: '需过磅',
                    value: '2'
                }]">
                                                    </td>
                                                </tr>
                                                <tr>
                                                    <td colspan="1" class="tdText">
                                                        <label style="width:40%;text-align:right;">结算标识：</label>
                                                        <input class="easyui-combobox" id="inqIsSettle"
                                                            name="inqIsSettle" style="width: 60%;" data-options="required:true,valueField: 'value',editable:false,
            textField: 'label',panelHeight:'auto',data: [{
                label: '按原发数结算',
                value: '1'
            },{
                label: '按实收数结算',
                value: '2'
            }]">
                                                    </td>
                                                    <td colspan="1" class="tdText">
                                                        <label style="width:40%;text-align:right;">币种代码 ：</label>
                                                        <input class="easyui-combobox" id="inqCurrencyCode"
                                                            name="inqCurrencyCode" style="width: 60%;" data-options="required:true,valueField: 'value',editable:false,
                textField: 'label',panelHeight:'auto', url: 'sysDict/queryItemByTypeName?dicName=币种',
                method: 'get',
                valueField: 'dicValue',
                textField: 'dicName'">
                                                    </td>
                                                    <td colspan="1" class="tdText">
                                                        <label style="width:40%;text-align:right;">付款条件：</label>
                                                        <input class="easyui-combobox" id="cobPayment" name="cobPayment"
                                                            style="width: 60%;" data-options="required:true,editable:false, url:'sysDict/queryItemByTypeName?dicName=付款条件',
                                                            method: 'get',
                                                            valueField: 'dicValue',
                                                            textField: 'dicName'">
                                                    </td>
                                                </tr>
                                                <tr>
                                                    <td colspan="1" class="tdText"><label
                                                            style="width: 40%; text-align: right;">合同起始时间：</label>
                                                        <input data-options="required:true,editable:false"
                                                            id="inqContractStart" class="easyui-datebox"
                                                            style="width: 60%">
                                                    </td>
                                                    <td colspan="1" class="tdText"><label
                                                            style="width: 40%; text-align: right;">合同结束时间：</label>
                                                        <input data-options="required:true,editable:false"
                                                            id="inqContractEnd" class="easyui-datebox"
                                                            style="width: 60%">
                                                    </td>
                                                    <td colspan="1" class="tdText"><label
                                                            style="width: 40%; text-align: right;">原合同编码：</label>
                                                        <input data-options="disabled:true" id="resCode"
                                                            class="easyui-textbox" style="width: 60%">
                                                    </td>
                                                </tr>
                                                <tr style="margin-bottom: 10px">

                                                    <td colspan="3" style="width: 800px;padding-left: 60px;"><label
                                                            style="width: 40%; text-align: right;">备注：</label> <input
                                                            id="remark" class="easyui-textbox"
                                                            style="width: 60%;height: 100px"
                                                            data-options="readonly:false,multiline:true">
                                                    </td>

                                                </tr>
                                            </table>
                                        </form>
                                    </div>
                                    <div title="报价明细">
                                        <table id="mmOffers"></table>
                                    </div>
                                    <div title="附件" style="padding: 5px;">
                                        <table>
                                            <tr>
                                                <td colspan="3"><input type="button" id="uploadbtn" value="选择文件..." />
                                                    <input type="file" id="uploadpicker" accept=""
                                                        onchange="changeFile()" multiple style="display: none;" />
                                                    <span>（文件名称不能包含斜杠、空格、&、#等特殊字符）</span>
                                                </td>
                                            </tr>
                                            <tr>
                                                <td><label style="width: 40%; text-align: right;">附件下载：</label>
                                                    <ul id="checkfileList"></ul>
                                                </td>
                                            </tr>
                                        </table>
                                    </div>
                                </div>
                            </div>
                            <%-- 创建采购订单窗口 --%>
                                <div id="add" class="easyui-window" closed="true" modal="true" title="创建采购订单"
                                    style="width: 930px; height: 230px; padding: 5px 5px; top: 50px">
                                    <form id="frmInquiry">
                                        <div id="createTabs" class="easyui-tabs" style="width: 890px; height: 150px">
                                            <div title="基础信息" style="padding: 5px;">
                                                <table>
                                                    <tr style="margin-bottom: 10px">
                                                        <td colspan="1" class="tdText">
                                                            <div onclick="selectInquiryResult()">
                                                                <label
                                                                    style="width: 40%; text-align: right;">采购合同：</label>
                                                                <input data-options="prompt:'点击查询采购合同'"
                                                                    name="oldOrdName" id="oldOrdName"
                                                                    class="easyui-textbox" style="width: 60%" /> <input
                                                                    type="hidden" id="oldOrdId">
                                                            </div>
                                                        </td>
                                                        <td colspan="1" class="tdText"><label
                                                                style="width: 40%; text-align: right;">原合同编码：</label>
                                                            <input id="oldOrdCode" class="easyui-textbox"
                                                                style="width: 50%">
                                                        </td>
                                                        <!-- <td colspan="1" class="tdText"><label
                                                                style="width: 40%;">原合同名称：</label>
                                                            <input id="oldOrdName" class="easyui-textbox"
                                                                style="width: 50%">
                                                        </td> -->
                                                    </tr>
                                                    <tr style="margin-bottom: 10px">
                                                        <td colspan="1" class="tdText"><label
                                                                style="width: 50%;">费用：</label>
                                                            <input id="oldOrdFreight" class="easyui-textbox"
                                                                style="width: 50%">
                                                        </td>
                                                        <td colspan="1" class="tdText"><label
                                                                style="width: 40%; text-align: right;">供应商编码：</label>
                                                            <input id="oldInfCode" class="easyui-textbox"
                                                                style="width: 50%">
                                                        </td>
                                                        <td colspan="1" class="tdText"><label
                                                                style="width: 40%; text-align: right;">供应商名称：</label>
                                                            <input id="oldInfName" class="easyui-textbox"
                                                                style="width: 50%">
                                                        </td>
                                                    </tr>
                                                </table>
                                            </div>
                                        </div>
                                    </form>
                                </div>
                                <!-- 选择已提交的询价结果的弹窗 -->
                                <div id="selectInquiryResultWindow" class="easyui-window" closed="true" modal="true"
                                    title="询价结果列表" style="width: 900px; height: 400px; padding: 5px 5px">
                                    <!-- 搜索框 -->
                                    <label style="font-size: 12px;">创建时间：</label> <input class="easyui-datebox"
                                        id="startInquiryResultTime"
                                        data-options="required:true,showSeconds:false,formatter:myformatter,parser:myparser"
                                        value="" style="width: 150px"> <label style="font-size: 10px;">~</label> <input
                                        class="easyui-datebox" id="endInquiryResultTime"
                                        data-options="required:true,showSeconds:false,formatter:myformatter,parser:myparser"
                                        style="width: 150px" /> <a style="margin-left: 30px" href="javascript:void(0)"
                                        class="easyui-linkbutton" data-options="iconCls:'icon-search'"
                                        onclick="selectInquiryList()">查询</a> <a style="margin-left: 5px"
                                        href="javascript:void(0)" class="easyui-linkbutton"
                                        data-options="iconCls:'icon-ok'" onclick="addInquiry()">确定</a>
                                    <!--询价结果列表DataGrid  -->
                                    <table id="inquiryResultList"></table>
                                </div>
                    </div>
        </body>
        <script>
            var selectedFileList = [];//已选文件列表
            var succsessCount = 0;//上传成功文件个数
            var errorCount = 0;//上传失败文件个数
            /**
             * 条件查询订单列表
             */
            function searchOederList() {
                let startTime = $('#startTime').datebox('getValue')
                let endTime = $('#endTime').datebox('getValue')
                let status = $('#status').combobox('getValue')
                let dg = $('#initTable')
                dg.datagrid('enableFilter')
                dg.datagrid('load', {
                    startTime: startTime ? startTime : '',
                    endTime: endTime ? endTime : '',
                    status: status ? status : ''
                })
            }

            function exportOrderList() {
                let startTime = $('#startTime').datebox('getValue')
                let endTime = $('#endTime').datebox('getValue')
                let status = $('#status').combobox('getValue')
                var form = [];
                form.push('startTime=' + (startTime ? startTime : ''));
                form.push('endTime=' + (endTime ? endTime : ''));
                form.push('status=' + (status ? status : ''));
                let url = 'api/purchase/order/change/export'
                let xhr = new XMLHttpRequest()
                xhr.open('POST', url, true)
                xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                xhr.setRequestHeader('token', localStorage.getItem('token'));
                xhr.setRequestHeader('userType', localStorage.getItem('userType'));
                xhr.responseType = 'blob'
                xhr.onload = function () {
                    if (this.status == 200) {
                        let blob = this.response
                        let reader = new FileReader()
                        reader.readAsDataURL(blob)
                        reader.onload = function (e) {
                            let a = document.createElement('a')
                            a.download = '采购订单' + new Date().toLocaleDateString() + '-' + new Date().toLocaleTimeString() + '.xlsx'
                            a.href = e.target.result
                            $('body').append(a)
                            a.click()
                            $(a).remove()
                        }
                    }
                }
                xhr.send(form.join('&'))
            }

            /**
             * 新增方法
             */
            function addOrder() {
                $('#createTabs').tabs({
                    tools: [{
                        text: '保存',
                        iconCls: 'icon-ok',
                        handler: function () {
                            createOrder();
                        }
                    }]
                })
                $('#frmInquiry').form('clear')
                selectedFileList = []
                $("#checkfileList").empty();
                $('#add').window('open')
            }

            /**
             * 根据resId，创建采购订单
             */
            function createOrder() {
                let resId = $('#oldOrdId').val()
                if (!resId) return
                $.ajax({
                    type: 'get',
                    url: 'purchase/order/change/createOrder?ordId=' + resId,
                    dataType: 'json',
                    success: function (data) {
                        if (data.code != 60200) {
                            $.messager.alert('消息', data.msg);
                        } else {
                            $.messager.alert('消息', data.msg);
                            let dg = $('#initTable');
                            dg.datagrid('enableFilter');
                            dg.datagrid('load');
                            $('#add').window('close');
                        }
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        $.messager.alert('消息', errorThrown);
                    }
                })
            }

            /**
             * 删除订单
             */
            function deleteOrder() {
                let order = $('#initTable').datagrid('getSelected')
                if (!order) {
                    $.messager.alert('提示', '请选择一条数据')
                    return
                }
                let ordId = order.ordId
                $.ajax({
                    type: 'delete',
                    url: 'purchase/order/change/delete?ordId=' + ordId,
                    dataType: 'json',
                    success: function (data) {
                        if (data.code == 60200) {
                            $.messager.alert('消息', data.msg)
                            let dg = $('#initTable');
                            dg.datagrid('enableFilter');
                            dg.datagrid('load');
                        } else {
                            $.messager.alert('消息', data.msg)
                        }
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        $.messager.alert('消息', errorThrown);
                    }
                })
            }

            /**
             * 更新采购订单按钮
             */
            function updateOrder() {
                endEditingMMs();
                let order = $('#initTable').datagrid('getSelected')
                if (!order) {
                    $.messager.alert('提示', '请选择一条数据')
                    return
                }
                if (+order.status == '1') {
                    $.messager.alert('提示', '该数据已提交，不可再次编辑')
                    return
                }
                let ordId = order.ordId
                $.ajax({
                    type: 'get',
                    url: 'purchase/order/change/selectInfor?ordId=' + ordId,
                    dataType: 'json',
                    success: function (data) {
                        if (data.code == 60200) {
                            let order = data.data
                            setOrderValue(order)
                        } else {
                            $.messager.alert('消息', data.msg);
                        }
                    }
                })

            }

            /**
             * 编辑、详情赋值
             */
            function setOrderValue(order) {
                if (+order.status == '0') {
                    $('#tabs').tabs({
                        tools: [{
                            text: '保存',
                            iconCls: 'icon-save',
                            handler: function () {
                                saveOrder('save');
                            }
                        }, {
                            text: '提交',
                            iconCls: 'icon-ok',
                            handler: function () {
                                $.messager.confirm('提示', '提交后无法再次编辑，确定要提交吗?（注意：oa退回后不要删除及转发流程，需先在cmp撤回）',
                                    function (r) {
                                        if (r) {
                                            saveOrder('submit');
                                        }
                                    });
                            }
                        }]
                    })
                } else {
                    $('#tabs').tabs({
                        tools: null
                    })
                }
                // 基本信息 
                $('#ordId').val(order.ordId)
                $('#resId').val(order.resId)
                $('#infId').val(order.infId); // 供应商ID
                $('#infCode').textbox('setValue', order.infCode); // 供应商编码
                $('#infName').textbox('setValue', order.infName); // 供应商编码
                $('#ordCode').textbox('setValue', order.ordCode)
                $('#ordName').textbox('setValue', order.ordName)
                $('#ordContractType').combobox('setValue', '1')
                // $('#ordCurrency').combobox('setValue', order.ordCurrency)
                $('#ordFreight').textbox('setValue', order.ordFreight)
                // $('#ordIncidental').textbox('setValue', order.ordIncidental)
                $('#ordSignAddress').textbox('setValue', order.ordSignAddress)
                $('#ordSignDate').datebox('setValue', order.ordSignDate)
                // $('#ordResultDate').datebox('setValue', order.ordResultDate)
                $('#ordIsSign').combobox('setValue', order.ordIsSign)
                // $('#ordContractId').val(order.ordContractId)
                // $('#ordContractName').textbox('setValue', order.ordContractName)
                $('#inqContractStart').datebox('setValue', order.inqContractStart)
                $('#inqContractEnd').datebox('setValue', order.inqContractEnd)
                $('#resCode').textbox('setValue', order.oldOrdCode)
                $('#remark').textbox('setValue', order.remark)
                // 取得附件列表
                getFileList(order)
                // 取得询价结果的供应商列表及报价明细
                // getResult(order.resId, order.infId)
                if (order.orderChangeSupplyModel.inqPaymentCode) {
                    $('#cobPayment').combobox('setValue', order.orderChangeSupplyModel.inqPaymentCode);
                } else {
                    // $('#cobPayment').combobox('setValue', 'Z001');
                }
                if (order.orderChangeSupplyModel.inqCurrencyCode) {
                    $('#inqCurrencyCode').combobox('setValue', order.orderChangeSupplyModel.inqCurrencyCode);
                } else {
                    $('#inqCurrencyCode').combobox('setValue', 'CNY');
                }
                if (order.orderChangeSupplyModel.inqIsWeight) {
                    $('#inqIsWeight').combobox('setValue', order.orderChangeSupplyModel.inqIsWeight);
                }
                if (order.orderChangeSupplyModel.inqIsSettle) {
                    $('#inqIsSettle').combobox('setValue', order.orderChangeSupplyModel.inqIsSettle);
                }
                if (order.orderChangeSupplyModel.inqIsOwn) {
                    $('#inqIsOwn').combobox('setValue', order.orderChangeSupplyModel.inqIsOwn);
                }

                setMmsOfferDatagrid(order.orderChangeMmModels)
                $('#edit').window('open')
                $('#tabs').tabs('select', 0);
            }

            /**
             * 详情
             * @param index
             */
            function orderDetail(index) {
                endEditingMMs();
                const rows = $('#initTable').datagrid('getRows')
                let row = rows[index]
                console.log('row', row);
                let ordId = row.ordId
                $.ajax({
                    type: 'get',
                    url: 'purchase/order/change/selectInfor?ordId=' + ordId,
                    dataType: 'json',
                    success: function (data) {
                        if (data.code == 60200) {
                            let order = data.data
                            setOrderValue(order)
                        } else {
                            $.messager.alert('消息', data.msg);
                        }
                    }
                })
            }

            /**
             * 保存附件
             */

            function saveAttch(row, obj, action) {
                obj.ordId = row
                let saveNum = 0
                if (selectedFileList.length > 0) {
                    $.each(selectedFileList, function (index, item) {
                        showFilediv();
                        var dataform = new FormData();
                        dataform.append("file", item);
                        var xmlhttp = null;
                        if (window.XMLHttpRequest) {// code for all new browsers
                            xmlhttp = new XMLHttpRequest();
                        } else if (window.ActiveXObject) {// code for IE5 and IE6
                            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
                        }
                        if (xmlhttp != null) {
                            xmlhttp.open("POST", "api/file/springUpload?fileRow=" + row
                                + "&fileTable=purchase_order_change&fileName="
                                + item.name, true);
                            xmlhttp.setRequestHeader('token', localStorage.getItem('token'));
                            xmlhttp.setRequestHeader('userType', localStorage.getItem('userType'));
                            xmlhttp.send(dataform);
                            xmlhttp.onreadystatechange = callbackMethods;
                        } else {
                            alert("你的浏览器版本不兼容，请使用更高版本的浏览器");
                        }

                        function callbackMethods() {
                            if (xmlhttp.readyState == 4) {
                                if (xmlhttp.status == 200) {
                                    saveNum += 1
                                    if (saveNum == selectedFileList.length) {
                                        hideFilediv();
                                        if ('submit' == action) {
                                            commitOrder(obj)
                                        }
                                    }
                                }
                            } else {
                                if (xmlhttp.status == 500) {
                                }
                            }
                        }
                    });
                } else {
                    if ('submit' == action) {
                        commitOrder(obj)
                    }
                }
            }

            /**
             * 保存
             */
            function saveOrder(action) {
                if (!$('#frmOrder').form('validate')) {
                    alert('有未填写数据！');
                    return;
                }
                if (endEditingMMs()) {
                    $('#mmOffers').datagrid('acceptChanges');
                }
                // 调用后台接口保存
                let supplyDeal = {
                    infId: $('#infId').val(),
                    inqPaymentCode: $('#cobPayment').combobox('getValue'),
                    inqPayment: $('#cobPayment').combobox('getText'),
                    inqCurrencyCode: $('#inqCurrencyCode').combobox('getValue'),
                    inqCurrency: $('#inqCurrencyCode').combobox('getText'),
                    inqIsWeight: $('#inqIsWeight').combobox('getValue'),
                    inqIsSettle: $('#inqIsSettle').combobox('getValue'),
                    inqIsOwn: $('#inqIsOwn').combobox('getValue')
                };
                //成交总数量
                let totalDealNumT = 0
                // 成交总金额（中标总金额）
                let dealTotalPriceT = 0
                let supplyDealMms = $('#mmOffers').datagrid('getRows');
                for (var supplyDealMm of supplyDealMms) {
                    // if (supplyDealMm.dealNum) {
                    if (supplyDealMm.inqIsFree == '1' && supplyDealMm.dealUnitPrice <= 0) {
                        alert('中标物资为付费标记时,单价不能为0');
                        return;
                    }
                    if (supplyDealMm.inqIsFree == 'X' && supplyDealMm.dealUnitPrice > 0) {
                        alert('中标物资单价大于0时，不能为免费标记时');
                        return;
                    }
                    //  }
                    console.log('supplyDealMm', supplyDealMm);
                    if (!supplyDealMm.inqStockAddress) {
                        alert(supplyDealMm.mmCode + ':请选择库存地点等必填信息!');
                        return;
                    }
                    supplyDealMm.dealTotalPrice = (Number(supplyDealMm.dealNum) * Number(supplyDealMm.dealUnitPrice)).toFixed(2);
                    supplyDealMm.inqTransportTotalPrice = Number(supplyDealMm.dealNum) * Number(supplyDealMm.inqTransportUnitPrice)
                    totalDealNumT += Number(supplyDealMm.dealNum)
                    dealTotalPriceT += Number(supplyDealMm.dealTotalPrice)
                }
                supplyDeal.infNum = totalDealNumT;
                supplyDeal.infLastTotalPrice = dealTotalPriceT;
                let ordId = $('#ordId').val()
                const orderModel = {
                    ordId: ordId,
                    resId: $('#resId').val(),
                    infId: $('#infId').val(), // 供应商ID
                    infCode: $('#infCode').textbox('getValue'), // 供应商编码
                    infName: $('#infName').textbox('getValue'), // 供应商编码
                    ordCode: $('#ordCode').textbox('getValue'),
                    ordName: $('#ordName').textbox('getValue'),
                    ordContractType: $('#ordContractType').combobox('getValue'),
                    // ordCurrency: $('#ordCurrency').combobox('getValue'),
                    ordFreight: dealTotalPriceT,
                    // ordIncidental: $('#ordIncidental').textbox('getValue'),
                    ordSignAddress: $('#ordSignAddress').textbox('getValue'),
                    ordSignDate: $('#ordSignDate').datebox('getValue'),
                    // ordResultDate: $('#ordResultDate').datebox('getValue'),
                    ordIsSign: $('#ordIsSign').combobox('getValue'),
                    // ordContractId: $('#ordContractId').val(),
                    // ordContractName: $('#ordContractName').textbox('getValue'),
                    inqContractStart: $('#inqContractStart').datebox('getValue'),
                    inqContractEnd: $('#inqContractEnd').datebox('getValue'),
                    // 买受人信息
                    /* ordDeptCode: $('#ordDeptCode').textbox('getValue'),
                     ordDeptName: $('#ordDeptName').textbox('getValue'),
                     ordLegal: $('#ordLegal').textbox('getValue'),
                     ordDeptAddress: $('#ordDeptAddress').textbox('getValue'),
                     ordPostal: $('#ordPostal').textbox('getValue'),
                     ordCredit: $('#ordCredit').textbox('getValue'),
                     ordFax: $('#ordFax').textbox('getValue'),
                     ordBank: $('#ordBank').textbox('getValue'),
                     ordBranchBank: $('#ordBranchBank').textbox('getValue'),
                     ordSettlNum: $('#ordSettlNum').textbox('getValue'),
                     ordDetails: $('#ordDetails').textbox('getValue'),*/
                    remark: $('#remark').textbox('getValue'),
                    orderChangeSupplyModel: supplyDeal,
                    orderChangeMmModels: supplyDealMms,
                    status: '0'
                }
                saveAjax(orderModel, action)
            }

            function saveAjax(obj, action) {
                let ordId = obj.ordId
                $.ajax({
                    type: 'post',
                    url: 'purchase/order/change/save',
                    data: JSON.stringify(obj),
                    dataType: 'json',
                    contentType: "application/json",
                    success: function (data) {
                        if (data.code == 60200) {
                            $('#ordCode').textbox('setValue', data.data.ordCode);
                            obj.ordCode = data.data.ordCode;
                            saveAttch(ordId, obj, action)
                            if ('save' == action) {
                                $.messager.alert('消息', data.msg.substr(0, 1500));
                                let dg = $('#initTable');
                                dg.datagrid('enableFilter');
                                dg.datagrid('load');
                                $('#edit').window('close');
                            }

                        } else {
                            if (data.msg.indexOf('外部参考:,无评估类型可以用于此项目') > -1) {
                                $.messager.alert('消息', '物资所选评估类型不正确，请先在采购计划页面检查并重新编辑保存！(非备品配件时为空，LP表示项目用途，LN表示普通用途)');
                            } else if (data.msg.indexOf('请输入评估类型') > -1) {
                                $.messager.alert('消息', '物资所选评估类型不正确，请先在采购计划页面检查并重新编辑保存！(非备品配件时为空，LP表示项目用途，LN表示普通用途)');
                            } else {
                                $.messager.alert('消息', data.msg.substr(0, 1500));
                            }
                        }
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        $.messager.alert('消息', errorThrown);
                    }
                })
            }

            /**
             * 提交的ajax
             */
            function commitOrder(obj) {
                obj.status = '1'
                $.ajax({
                    type: "post",
                    dataType: "json",
                    url: 'purchase/order/change/commit',
                    data: JSON.stringify(obj),
                    contentType: "application/json",
                    success: function (data) {
                        if (data.code != 60200) {
                            $.messager.alert('消息', data.msg);
                        } else {
                            $.messager.alert('消息', data.msg);
                            let dg = $('#initTable');
                            dg.datagrid('enableFilter');
                            dg.datagrid('load');
                            $('#edit').window('close');
                        }
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        $.messager.alert('消息', errorThrown);
                    }
                })
            }

            /**
             * 查询询价结果列表的方法
             */

            // 设置询价结果dataGrid
            function setInquiriesDataGrid() {
                // 构建查询询价结果的dataGrid
                let startTime = $('#startInquiryResultTime').datebox('getValue')
                let endTime = $('#endInquiryResultTime').datebox('getValue')
                let inquiryResultDataGrid = $('#inquiryResultList')
                inquiryResultDataGrid.datagrid({
                    title: '采购订单',
                    queryParams: {
                        startTime: startTime ? startTime : '',
                        endTime: endTime ? endTime : '',
                        status: '2',
                        inqActualId: PUser.superadmin == '1' ? null : PUser.userid
                    },
                    url: 'purchase/order/selectList',
                    iconCls: 'icon-application',
                    clientPaging: false,
                    remoteFilter: true,
                    filterDelay: 0,
                    width: 860,
                    height: 300,
                    nowrap: true,
                    rownumbers: true,
                    animate: false,
                    collapsible: false,
                    singleSelect: true,
                    pageSize: 10,
                    remoteSort: true,
                    pagination: true,
                    frozenColumns: [[
                        {
                            field: 'ordId',
                            title: '订单Id',
                            hidden: true,
                            width: 100,
                            formatter: function (val, rec) {
                                return unescape(val)
                            }
                        },
                        {
                            field: 'resId',
                            title: '询价结果id',
                            hidden: true,
                            width: 100,
                            formatter: function (val, rec) {
                                return unescape(val)
                            }
                        },
                        {
                            field: 'infId',
                            title: '供应商id',
                            hidden: true,
                            width: 100,
                            formatter: function (val, rec) {
                                return unescape(val)
                            }
                        },
                        {
                            field: 'ordCode',
                            title: '订单编号',
                            sortable: true,
                            formatter: function (val, rec, index) {
                                return (val ? val : '')
                            }
                        },
                        {
                            field: 'ordName',
                            title: '订单名称',
                            sortable: true,
                            formatter: function (val, rec, index) {
                                return (val ? val : '')
                            }
                        },
                        {
                            field: 'resCode',
                            title: '结果编码',
                            sortable: true,
                            formatter: function (val, rec, index) {
                                return unescape(val ? val : '')

                            }
                        },]],
                    columns: [
                        [
                            {
                                field: 'infName',
                                title: '供应商名称',
                                sortable: true,
                                formatter: function (val, rec, index) {
                                    return unescape(val ? val : '')

                                }
                            },
                            {
                                field: 'infCode',
                                title: '供应商编码',
                                sortable: true,
                                formatter: function (val, rec, index) {
                                    return unescape(val ? val : '')

                                }
                            },
                            {
                                field: 'ordContractType',
                                title: '是否推送OA',
                                sortable: true,
                                formatter: function (val, rec) {
                                    return unescape(val == '1' ? '是' : '否')
                                }
                            },
                            {
                                field: 'ordIsSign',
                                title: '是否框架',
                                sortable: true,
                                formatter: function (val, rec) {
                                    return unescape(val == '1' ? '是' : '否')
                                }
                            },
                            {
                                field: 'ordFreight',
                                title: '费用',
                                sortable: true,
                                formatter: function (val, rec) {
                                    return unescape(val ? val.toLocaleString() : '')
                                }
                            },
                            // {
                            //     field: 'ordIncidental',
                            //     title: '杂费',
                            //     sortable: true,
                            //     formatter: function (val, rec) {
                            //         return unescape(val ? val : '')
                            //     }
                            // },
                            {
                                field: 'ordSignAddress',
                                title: '签订地点',
                                sortable: true,
                                formatter: function (val, rec) {
                                    return unescape(val ? val : '')
                                }
                            },
                            {
                                field: 'inqContractStart',
                                title: '合同起始日期',
                                sortable: true,
                                formatter: function (val, rec) {
                                    return unescape(val ? val : '')
                                }
                            },
                            {
                                field: 'inqContractEnd',
                                title: '合同结束日期',
                                sortable: true,
                                formatter: function (val, rec) {
                                    return unescape(val ? val : '')
                                }
                            },
                            {
                                field: 'oaFlowId',
                                title: 'oa流程id',
                                sortable: true,
                                formatter: function (val, rec) {
                                    return unescape(val ? val : '')
                                }
                            },
                            {
                                field: 'createName',
                                title: '创建人',
                                sortable: true,
                                formatter: function (val, rec) {
                                    return unescape(val ? val : '')
                                }
                            },
                            {
                                field: 'createTime',
                                title: '创建时间',
                                sortable: true,
                                formatter: function (val, rec) {
                                    return unescape(val ? val : '')
                                }
                            },
                            {
                                field: 'updateTime',
                                title: '更新时间',
                                sortable: true,
                                formatter: function (val, rec) {
                                    return unescape(val ? val : '')
                                }
                            },
                            {
                                field: 'status',
                                title: '状态',
                                sortable: true,
                                formatter: function (val, rec) {
                                    let status = val ? val : '';
                                    return unescape(status == '0' ? '待提交' : (status == '2' ? '已完成' : '已提交'));
                                }
                            }
                        ]
                    ],
                    toolbar: [
                        //     {
                        //     text: '确定',
                        //     iconCls: 'icon-ok',
                        //     handler: function () {

                        //     }
                        // }
                    ],
                    onLoadSuccess: function () {

                    },
                })
                inquiryResultDataGrid.datagrid('enableFilter');
            }

            function addInquiry() {
                let inquiryResultDataGrid = $('#inquiryResultList')
                let result = inquiryResultDataGrid.datagrid('getSelected')
                if (result) {
                    console.log('selectrow:', result);
                    $('#oldOrdId').val(result.ordId)
                    $('#oldOrdCode').textbox('setValue', result.ordCode)
                    $('#oldOrdName').textbox('setValue', result.ordName)
                    $('#oldOrdFreight').textbox('setValue', result.ordFreight)
                    $('#oldInfCode').textbox('setValue', result.infCode)
                    $('#oldInfName').textbox('setValue', result.infName)
                    $('#selectInquiryResultWindow').window('close')
                } else {
                    $.messager.alert('提示', '请选择一条数据')
                    return
                }

            }

            function selectInquiryResult() {
                selectInquiryList();
                $('#selectInquiryResultWindow').window('open')
            }

            /**
             * 初始化采购订单列表
             */
            function bingGrid() {
                let startTime = $('#startTime').datebox('getValue');
                let endTime = $('#endTime').datebox('getValue');
                let status = $('#status').combobox('getValue');
                let dg = $('#initTable');
                dg.datagrid({
                    title: '',
                    queryParams: {
                        startTime: startTime ? startTime : '',
                        endTime: endTime ? endTime : '',
                        status: status
                    },
                    url: 'purchase/order/change/selectList',
                    iconCls: 'icon-application',
                    clientPaging: false,
                    remoteFilter: true,
                    filterDelay: 0,
                    width: getWidth(0.98),
                    height: 400,
                    nowrap: true,
                    rownumbers: true,
                    animate: false,
                    collapsible: false,
                    singleSelect: true,
                    pageSize: 10,
                    remoteSort: true,
                    pagination: true,
                    frozenColumns: [[
                        {
                            field: 'ordId',
                            title: '订单Id',
                            hidden: true,
                            width: 100,
                            formatter: function (val, rec) {
                                return unescape(val)
                            }
                        },
                        {
                            field: 'resId',
                            title: '询价结果id',
                            hidden: true,
                            width: 100,
                            formatter: function (val, rec) {
                                return unescape(val)
                            }
                        },
                        {
                            field: 'infId',
                            title: '供应商id',
                            hidden: true,
                            width: 100,
                            formatter: function (val, rec) {
                                return unescape(val)
                            }
                        },
                        {
                            field: 'ordCode',
                            title: '订单编号',
                            sortable: true,
                            formatter: function (val, rec, index) {
                                return '<a href="javascript:void(0)" onclick="orderDetail(' + index +
                                    ')">' + (val ? val : '') + '</a>'
                            }
                        },
                        {
                            field: 'ordName',
                            title: '订单名称',
                            sortable: true,
                            formatter: function (val, rec, index) {
                                return '<a href="javascript:void(0)" onclick="orderDetail(' + index +
                                    ')">' + (val ? val : '') + '</a>'
                            }
                        },
                        {
                            field: 'oldOrdCode',
                            title: '原合同编码',
                            sortable: true,
                            formatter: function (val, rec, index) {
                                return unescape(val ? val : '')

                            }
                        },
                        {
                            field: 'oldOrdName',
                            title: '原合同名称',
                            sortable: true,
                            formatter: function (val, rec, index) {
                                return unescape(val ? val : '')

                            }
                        },]],
                    columns: [
                        [
                            {
                                field: 'infName',
                                title: '供应商名称',
                                sortable: true,
                                formatter: function (val, rec, index) {
                                    return unescape(val ? val : '')

                                }
                            },
                            {
                                field: 'infCode',
                                title: '供应商编码',
                                sortable: true,
                                formatter: function (val, rec, index) {
                                    return unescape(val ? val : '')

                                }
                            },
                            {
                                field: 'ordContractType',
                                title: '是否推送OA',
                                sortable: true,
                                formatter: function (val, rec) {
                                    return unescape(val == '1' ? '是' : '否')
                                }
                            },
                            {
                                field: 'ordIsSign',
                                title: '是否框架',
                                sortable: true,
                                formatter: function (val, rec) {
                                    return unescape(val == '1' ? '是' : '否')
                                }
                            },
                            {
                                field: 'ordFreight',
                                title: '费用',
                                sortable: true,
                                formatter: function (val, rec) {
                                    return unescape(val ? val.toLocaleString() : '')
                                }
                            },
                            // {
                            //     field: 'ordIncidental',
                            //     title: '杂费',
                            //     sortable: true,
                            //     formatter: function (val, rec) {
                            //         return unescape(val ? val : '')
                            //     }
                            // },
                            {
                                field: 'ordSignAddress',
                                title: '签订地点',
                                sortable: true,
                                formatter: function (val, rec) {
                                    return unescape(val ? val : '')
                                }
                            },
                            {
                                field: 'inqContractStart',
                                title: '合同起始日期',
                                sortable: true,
                                formatter: function (val, rec) {
                                    return unescape(val ? val : '')
                                }
                            },
                            {
                                field: 'inqContractEnd',
                                title: '合同结束日期',
                                sortable: true,
                                formatter: function (val, rec) {
                                    return unescape(val ? val : '')
                                }
                            },
                            {
                                field: 'oaFlowId',
                                title: 'oa流程id',
                                sortable: true,
                                formatter: function (val, rec) {
                                    return unescape(val ? val : '')
                                }
                            },
                            {
                                field: 'createName',
                                title: '创建人',
                                sortable: true,
                                formatter: function (val, rec) {
                                    return unescape(val ? val : '')
                                }
                            },
                            {
                                field: 'createTime',
                                title: '创建时间',
                                sortable: true,
                                formatter: function (val, rec) {
                                    return unescape(val ? val : '')
                                }
                            },
                            {
                                field: 'updateTime',
                                title: '更新时间',
                                sortable: true,
                                formatter: function (val, rec) {
                                    return unescape(val ? val : '')
                                }
                            },
                            {
                                field: 'status',
                                title: '状态',
                                sortable: true,
                                formatter: function (val, rec) {
                                    let status = val ? val : '';
                                    return unescape(status == '0' ? '待提交' : (status == '2' ? '已完成' : '已提交'));
                                }
                            }
                        ]
                    ],
                    toolbar: [{
                        text: '新增',
                        iconCls: 'icon-add',
                        handler: function () {
                            addOrder();
                        }
                    },
                        '-',
                    {
                        text: '编辑',
                        iconCls: 'icon-edit',
                        handler: function () {
                            var obj = document.getElementById('uploadpicker');
                            obj.outerHTML = obj.outerHTML;
                            updateOrder();
                        }
                    },
                        '-',
                    {
                        text: '删除',
                        iconCls: 'icon-cancel',
                        handler: function () {
                            //删除
                            let row = $('#initTable').datagrid('getSelected');
                            if (row) {
                                $.messager.confirm('提示', '确定要删除吗?',
                                    function (r) {
                                        if (r) {
                                            deleteOrder(row.ordId);
                                        }
                                    });
                            } else {
                                $.messager.alert('消息', '请选中一个要删除的数据');
                            }
                        }
                    }, '-',
                    {
                        text: '撤回',
                        iconCls: 'icon-undo',
                        handler: function () {
                            //撤回
                            let row = $('#initTable').datagrid('getSelected');
                            if (row) {
                                if (row.status == '2') {
                                    $.messager.alert('提示', '该单据已完成，无法撤回')
                                    return
                                }
                                if (row.status != '1') {
                                    $.messager.alert('提示', '该单据已完成，无法撤回')
                                    return
                                }
                                $.messager.confirm('提示', '确定要撤回该采购订单吗?',
                                    function (r) {
                                        if (r) {
                                            backupOrder(row);
                                        }
                                    });
                            } else {
                                $.messager.alert('消息', '请选择要撤回的采购订单。');
                                return
                            }
                        }
                    }
                    ],
                    onLoadSuccess: function () {

                    },
                    onDblClickRow: function () {
                        updateOrder();

                    }
                });
                dg.datagrid('enableFilter');
            }

            /**
             *  撤回采购订单
             */
            function backupOrder(orderObj) {
                $.ajax({
                    type: 'get',
                    url: 'purchase/order/change/back?ordId=' + orderObj.ordId,
                    // data: JSON.stringify(orderObj),
                    contentType: "application/json",
                    dataType: 'json',
                    success: function (data) {
                        if (data.code == 60200) {
                            $.messager.alert('消息', data.msg)
                            let dg = $('#initTable');
                            dg.datagrid('enableFilter');
                            dg.datagrid('load');
                        } else {
                            $.messager.alert('消息', data.msg)
                        }
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        $.messager.alert('消息', errorThrown);
                    }
                })
            }

            /**
             * 设置工具栏按钮
             * @param action
             * @param row
             */
            function setTabToolBar(action, row = null) {
                if (action !== 'detail') {
                    $('#tabs').tabs({
                        tools: [{
                            text: '保存',
                            iconCls: 'icon-save',
                            handler: function () {
                                saveOrder('save');
                            }
                        }, {
                            text: '提交',
                            iconCls: 'icon-ok',
                            handler: function () {
                                $.messager.confirm('提示', '提交后无法再次编辑，确定要提交吗?',
                                    function (r) {
                                        if (r) {
                                            saveOrder('submit');
                                        }
                                    });
                            }
                        }]
                    })
                } else {
                    $('#tabs').tabs({
                        tools: ''
                    })
                }
            }

            //查询询价书
            function selectInquiryList() {
                let startTime = $('#startInquiryResultTime').datebox('getValue');
                let endTime = $('#endInquiryResultTime').datebox('getValue');
                let dg = $('#inquiryResultList');
                dg.datagrid('enableFilter');
                dg.datagrid('load', {
                    startTime: startTime ? startTime : '',
                    endTime: endTime ? endTime : '',
                    status: '2',
                    inqActualId: PUser.superadmin == '1' ? null : PUser.userid
                })
            }

            /**
             *根据resId查询结果详情
             */
            function getResult(resId, infId) {
                $.ajax({
                    type: 'get',
                    dataType: 'json',
                    url: "purchase/result/selectResultMmInfo?resId=" + resId + "&infId=" + infId,
                    success: function (data) {
                        if (data.code != 60200) {
                            $.messager.alert('消息', '未查询到数据');
                        } else {
                            console.log(data.data)
                            const purchaseSupplyDealMm = data.data
                            if (!purchaseSupplyDealMm) return
                            setMmsOfferDatagrid(purchaseSupplyDealMm)
                        }
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        $.messager.alert('消息', errorThrown);
                    }
                })
                $('#resultDetaillWindow').window('open');
                $('#tabs').tabs('select', 0)
            }


            var dealIsCheckOptions = [{
                "dealIsCheck": "0",
                "text": "否"
            }, {
                "dealIsCheck": "1",
                "text": "是"
            }];
            var inqIsSettleOptions = [{
                "inqIsSettle": "1",
                "text": "按原发数结算"
            }, {
                "inqIsSettle": "2",
                "text": "按实收数结算"
            }];
            var inqIsWeightOptions = [{
                "inqIsWeight": "1",
                "text": "无需过磅"
            }, {
                "inqIsWeight": "2",
                "text": "需过磅"
            }];
            var inqIsOwnOptions = [{
                "inqIsOwn": "1",
                "text": "自提"
            }, {
                "inqIsOwn": "2",
                "text": "供应商送货"
            }];

            var inqIsFreeOptions = [{
                "inqIsFree": "1",
                "text": "付费"
            }, {
                "inqIsFree": "X",
                "text": "免费"
            }];

            // var inqBackGoodOptions = [{
            //     "inqBackGood": "1",
            //     "text": "采购"
            // }, {
            //     "inqBackGood": "X",
            //     "text": "退货"
            // }];

            /**
             * 构建物资报价明细的datagrid
             */
            function setMmsOfferDatagrid(arr) {
                // 构建供应商物资报价明细
                let mmOffers = $('#mmOffers')
                mmOffers.datagrid({
                    // fitColumns: true,
                    data: arr,
                    iconCls: 'icon-application',
                    // clientPaging: true,
                    remoteFilter: false,
                    filterDelay: 0,
                    width: 860,
                    height: 300,
                    nowrap: true,
                    rownumbers: true,
                    animate: false,
                    collapsible: false,
                    singleSelect: true,
                    pageSize: 10,
                    remoteSort: false,
                    // pagination: true,
                    frozenColumns: [[{
                        field: 'infId',
                        title: '供应商Id',
                        hidden: true,
                        formatter: function (val, rec) {
                            return val ? unescape(val) : ''
                        }
                    },
                    {
                        field: 'resId',
                        title: '询价结果id',
                        hidden: true,
                        formatter: function (val, rec) {
                            return val ? unescape(val) : ''
                        }
                    },
                    {
                        field: 'inqId',
                        title: '询价id',
                        hidden: true,
                        formatter: function (val, rec) {
                            return val ? unescape(val) : ''
                        }
                    },

                    {
                        field: 'planId',
                        title: '归口编码',
                        formatter: function (val, rec) {
                            return val ? unescape(val) : ''
                        }
                    },
                    {
                        field: 'gramId',
                        title: '方案Id',
                        hidden: true,
                        sortable: true,
                        formatter: function (val, rec) {
                            return val ? unescape(val) : ''
                        }
                    },
                    {
                        field: 'mmCode',
                        title: '物资编码',
                        formatter: function (val, rec) {
                            return val ? val : ''
                        },
                    },
                    {
                        field: 'mmDetail',
                        title: '物资描述',
                        sortable: true,
                        width: 210,
                        formatter: function (val, rec) {
                            if (val) {
                                return '<span title="' + val + '">' + val + '</span>';
                            } else {
                                return val;
                            }
                        }
                    },]],
                    columns: [
                        [
                            {
                                field: 'mmUnit',
                                title: '计量单位',
                                sortable: true,
                                formatter: function (val, rec) {
                                    return unescape(val ? val : '')
                                }
                            },
                            {
                                field: 'mmUnitDetail',
                                title: '计量单位描述',
                                sortable: true,
                                formatter: function (val, rec) {
                                    return unescape(val ? val : '')
                                }
                            },
                            {
                                field: 'planFactoryCode',
                                title: '到货工厂',
                                formatter: function (val, rec) {
                                    return val ? val : ''
                                },
                            },
                            {
                                field: 'inqStockAddressCode',
                                title: '库存地点',
                                sortable: true,
                                width: 120,
                                editor: {
                                    type: 'combobox',
                                    options: {
                                        // url: addressUrl,
                                        method: 'get',
                                        valueField: "dicValue",
                                        textField: "dicName",
                                        editable: false,
                                        required: true
                                    }
                                },
                                formatter: function (val, rec) {
                                    return rec.inqStockAddress;
                                }
                            },
                            // {
                            //     field: 'inqBackGood',
                            //     title: '退货标记',
                            //     formatter: function (val, rec) {
                            //         return val == 'X' ? '退货' : '采购'
                            //     },
                            //     editor: {
                            //         type: 'combobox',
                            //         options: {
                            //             data: inqBackGoodOptions,
                            //             valueField: "inqBackGood",
                            //             textField: "text",
                            //             editable: false,
                            //             required: true
                            //         }
                            //     }
                            // },
                            {
                                field: 'inqIsFree',
                                title: '免费标记',
                                formatter: function (val, rec) {
                                    return val == 'X' ? '免费' : '付费'
                                },
                                editor: {
                                    type: 'combobox',
                                    options: {
                                        data: inqIsFreeOptions,
                                        valueField: "inqIsFree",
                                        textField: "text",
                                        editable: false,
                                        required: true
                                    }
                                }
                            },
                            {
                                field: 'inqOfrNum',
                                title: '报价数量',
                                formatter: function (val, rec) {
                                    return val ? val : ''
                                },
                                /*editor: {
                                    type: 'numberbox'
                                }*/
                            },
                            {
                                field: 'inqOfrUnitPrice',
                                title: '报价单价',
                                formatter: function (val, rec) {
                                    return val ? val : ''
                                },
                                /*editor: {
                                    type: 'numberbox'
                                }*/
                            },
                            {
                                field: 'inqOfrTotalPrice',
                                title: '报价金额',
                                formatter: function (val, rec) {
                                    return val ? val : ''
                                },
                                /*editor: {
                                    type: 'numberbox'
                                }*/
                            },
                            {
                                field: 'inqTransportUnitPrice',
                                title: '运费单价',
                                editor: {
                                    type: 'numberbox'
                                },
                                sortable: true,
                                formatter: function (val, rec) {
                                    return val ? unescape(val) : ''
                                }
                            },
                            {
                                field: 'inqTransportTotalPrice',
                                title: '运费金额',
                                /* editor: {
                                     type: 'numberbox'
                                 },*/
                                sortable: true,
                                formatter: function (val, rec) {
                                    return val ? unescape(val) : ''
                                }
                            },
                            /*{
                                field: 'inqOfrIncludePrice',
                                title: '含税价格',
                                editor: {
                                    type: 'numberbox'
                                },
                                sortable: true,
                                formatter: function (val, rec) {
                                    return val ? unescape(val) : ''
                                }
                            },*/

                            {
                                field: 'inqTaxNum',
                                title: '税码',
                                sortable: true,
                                width: 120,
                                editor: {
                                    type: 'combobox',
                                    options: {
                                        url: 'sysDict/queryItemByTypeName?dicName=税码',
                                        method: 'get',
                                        valueField: "dicValue",
                                        textField: "dicName",
                                        editable: false,
                                        required: false
                                    }
                                },
                                formatter: function (val, rec) {
                                    return rec.inqTaxRate;
                                }
                            },
                            {
                                field: 'inqDeliverDate',
                                title: '交货日期',
                                sortable: true,
                                editor: {
                                    type: 'datebox'
                                },
                                width: 120,
                                formatter: function (val, rec) {
                                    return val ? unescape(val) : ''
                                }
                            },
                            // {
                            //     field: 'inqOfrExcludePrice',
                            //     title: '不含税价格',
                            //     sortable: true,
                            //     editor: {
                            //         type: 'numberbox'
                            //     },
                            //     formatter: function (val, rec) {
                            //         return val ? unescape(val) : ''
                            //     }
                            // },
                            {
                                field: 'dealNum',
                                title: '中标数量',
                                editor: {
                                    type: 'numberbox',
                                    options: {
                                        required: true,
                                        precision: 4
                                    }
                                },
                                formatter: function (val, rec) {
                                    return val ? unescape(val) : ''
                                }
                            },
                            {
                                field: 'dealUnitPrice',
                                title: '中标单价',
                                editor: {
                                    type: 'numberbox',
                                    options: {
                                        required: true,
                                        precision: 2
                                    }
                                },
                                formatter: function (val, rec) {
                                    return val ? unescape(val) : ''
                                }
                            },
                            {
                                field: 'dealTotalPrice',
                                title: '中标金额',
                                sortable: true,
                                /*editor: {
                                    type: 'numberbox'
                                },*/
                                formatter: function (val, rec) {
                                    return val ? unescape(val.toLocaleString()) : ''
                                }
                            },
                            {
                                field: 'mmTypeCode',
                                title: '物料组编码',
                                sortable: true,
                                formatter: function (val, rec) {
                                    return val ? unescape(val.toLocaleString()) : ''
                                }
                            },
                            {
                                field: 'mmTypeName',
                                title: '物料组',
                                sortable: true,
                                formatter: function (val, rec) {
                                    return val ? unescape(val.toLocaleString()) : ''
                                }
                            },
                            {
                                field: 'gramUseName',
                                title: '联系人',
                                sortable: true,
                                width: 100,
                                formatter: function (val, rec) {
                                    return val ? unescape(val) : ''
                                }
                            },
                            {
                                field: 'gramUseTel',
                                title: '联系方式',
                                sortable: true,
                                width: 100,
                                formatter: function (val, rec) {
                                    return val ? unescape(val) : ''
                                }
                            },
                            {
                                field: 'remark',
                                title: '备注',
                                sortable: true,
                                formatter: function (val, rec) {
                                    return val ? unescape(val) : ''
                                }
                            },
                            {
                                field: 'createName',
                                title: '创建人',
                                sortable: true,
                                formatter: function (val, rec) {
                                    return val ? unescape(val) : ''
                                }
                            },
                            {
                                field: 'createTime',
                                title: '创建时间',
                                sortable: true,
                                formatter: function (val, rec) {
                                    return val ? unescape(val) : ''
                                }
                            },
                            {
                                field: 'updateTime',
                                title: '更新时间',
                                sortable: true,
                                formatter: function (val, rec) {
                                    return val ? unescape(val) : ''
                                }
                            },
                            /* {
                                 field: 'status ',
                                 title: '状态',
                                 sortable: true,
                                 width: 500,
                                 formatter: function (val, rec) {
                                     return val ? unescape(val) : ''
                                 }
                             }*/
                        ]
                    ],
                    onEndEdit: onEndEditMm,
                    onClickCell: onClickCellMm,
                    toolbar: [{
                        text: '一键填充',
                        iconCls: 'icon-down',
                        handler: function () {
                            $.messager.confirm("提示", "确认向下复制第一行库存地点等信息?", function (e) {
                                if (e) {
                                    if (endEditingMMs()) {
                                        var rows = $('#mmOffers').datagrid('getRows');
                                        for (let i = 1; i < rows.length; i++) {
                                            var row = rows[i];
                                            row.inqIsFree = rows[0].inqIsFree;
                                            // row.inqBackGood = rows[0].inqBackGood;
                                            row.inqStockAddressCode = rows[0].inqStockAddressCode;
                                            row.inqStockAddress = rows[0].inqStockAddress;
                                            row.inqDeliverDate = rows[0].inqDeliverDate;
                                            $('#mmOffers').datagrid('updateRow', { index: i, row: row });
                                            $('#mmOffers').datagrid('refreshRow', i);
                                        }
                                        //                                         $('#mmOffers').datagrid('acceptChanges');
                                        // $('#mmOffers').datagrid('reload');
                                    }
                                }
                            })
                        }
                    }, '-', {
                        text: '导出',
                        iconCls: 'icon-export',
                        handler: function () {
                            exportMmList();
                        }
                    }],
                })
            }

            // 导出采购计划列表
            function exportMmList() {
                let gramMmRows = $('#initTable').datagrid('getSelected');
                var form = [];
                form.push('ordId=' + gramMmRows.ordId);
                form.push('infId=' + gramMmRows.infId);
                let url = "api/purchase/order/change/mm/export";
                let xhr = new XMLHttpRequest()
                xhr.open('POST', url, true)
                xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                xhr.setRequestHeader('token', localStorage.getItem('token'));
                xhr.setRequestHeader('userType', localStorage.getItem('userType'));
                xhr.responseType = 'blob'
                xhr.onload = function () {
                    if (this.status == 200) {
                        let blob = this.response
                        let reader = new FileReader()
                        reader.readAsDataURL(blob)
                        reader.onload = function (e) {
                            let a = document.createElement('a')
                            a.download = '订单明细' + new Date().getTime() + '.xlsx'
                            a.href = e.target.result
                            $('body').append(a)
                            a.click()
                            $(a).remove()
                        }
                    }
                }
                xhr.send(form.join('&'))
            }

            var editIndexMm = undefined;
            // 行编辑结束
            function endEditingMMs() {
                if (editIndexMm == undefined) {
                    return true
                }
                console.log('editIndexMm===', editIndexMm)
                if ($('#mmOffers').datagrid('validateRow', editIndexMm)) {
                    $('#mmOffers').datagrid('endEdit', editIndexMm);
                    editIndexMm = undefined;
                    return true;
                } else {
                    alert('请先完成本行必填数据录入!');
                    return false;
                }
            }
            function onClickCellMm(index, field) {
                if (editIndexMm != index) {
                    if (endEditingMMs()) {
                        $('#mmOffers').datagrid('selectRow', index)
                            .datagrid('beginEdit', index);
                        var ed = $('#mmOffers').datagrid('getEditor', { index: index, field: field });
                        var row = $('#mmOffers').datagrid('getRows')[index];

                        var addressUrl = 'sysDict/queryItemByTypeName?dicName=' + row.planFactoryCode + '-库存地点';
                        //此处field为第二个下拉列的field
                        let appTarget = $('#mmOffers').datagrid('getEditor', {
                            index: index,
                            field: 'inqStockAddressCode'
                        }).target;

                        if (appTarget.combobox('getData').length == 0) {
                            //清空
                            appTarget.combobox('clear');
                            appTarget.combobox({
                                url: addressUrl,
                                method: 'get',
                                valueField: "dicValue",
                                textField: "dicName",
                                editable: false,
                                required: true
                            });
                            appTarget.combobox('setValue', row.inqStockAddressCode);
                        }
                        if (ed) {
                            //  ($(ed.target).data('textbox') ? $(ed.target).textbox('textbox') : $(ed.target)).focus();
                        }
                        editIndexMm = index;
                    } else {
                        setTimeout(function () {
                            $('#mmOffers').datagrid('selectRow', editIndexMm);
                        }, 0);
                    }
                }
            }

            function onEndEditMm(index, row) {
                var ed = $(this).datagrid('getEditor', {
                    index: index,
                    field: 'inqStockAddressCode'
                });
                row.inqStockAddress = $(ed.target).combobox('getText');
            }

            /************文件处理部分*************/
            /**
             *文件框改变事件
             */
            function changeFile() {
                var files = $("#uploadpicker").prop("files");
                $.each(
                    files,
                    function (index, item) {
                        var choiseFile = $("#checkfileList>li");
                        if (choiseFile.length > 0) {//文件去重
                            var count = 0;
                            $.each(choiseFile, function (index1, item1) {
                                if (item.name == item1.innerText) {
                                    count++;
                                }
                            });
                            if (count == 0) {
                                if (checkFileLength(item.size)) {
                                    if (item.name.includes('#') || item.name.includes('/') || item.name.includes('&') || item.name.includes('\\') || item.name.includes(' ')) {
                                        alert('文件名不能包含&、斜杠、反斜杠、空格等特殊字符！');
                                        return;
                                    }
                                    $("#checkfileList")
                                        .append(
                                            "<li class=\"fileinfo\">"
                                            + item.name
                                            + "<a style=\"display: none; color: red; margin-left: 10px;\" href=\"javascript:void(0)\" onclick=\"RemoveFile(this,'"
                                            + item.name
                                            + "')\">删除</a>"
                                            + "</li>");
                                    selectedFileList.push(item);
                                    AddMoushover();
                                }
                            }
                        } else {
                            if (checkFileLength(item.size)) {
                                if (item.name.includes('#') || item.name.includes('/') || item.name.includes('&') || item.name.includes('\\') || item.name.includes(' ')) {
                                    alert('文件名不能包含&、斜杠、反斜杠、空格等特殊字符！');
                                    return;
                                }
                                $("#checkfileList")
                                    .append(
                                        "<li class=\"fileinfo\">"
                                        + item.name
                                        + "<a style=\"display: none; color: red; margin-left: 10px;\" href=\"javascript:void(0)\" onclick=\"RemoveFile(this,'"
                                        + item.name
                                        + "')\">删除</a>"
                                        + "</li>");
                                selectedFileList.push(item);
                                // 										sselectedFileNameList.push(item.name);
                                AddMoushover();
                            }
                        }
                    });
            }

            /**
             *    判断文件是否超过限制大小
             * @param fileLen
             * @returns {boolean}
             */
            function checkFileLength(fileLen) {
                if (fileLen > 102400000) {
                    $.messager.alert("提示", "上传文件大小不能超过100M", "error");
                    return false;
                }
                return true;
            }

            /**
             * //添加鼠标经过事件，鼠标划过时显示“删除”
             * @constructor
             */
            function AddMoushover() {
                $(".fileinfo").hover(function () {
                    $(this).find("a").last().css("display", "");
                }, function () {
                    $(this).find("a").last().css("display", "none");
                });
            }

            /**
             *  移除已选择的文件
             */

            function RemoveFile(obj, fileId) {

                $.messager.confirm("提示", "确认删除当前文件?", function (e) {
                    if (e) {
                        let index = $("#checkfileList>li").index($(obj).parent());
                        selectedFileList.splice(index, 1);
                        $(obj).parent().remove();
                        // 					var index1 = $.inArray(filename, sselectedFileNameList);
                        // 					sselectedFileNameList.splice(index1, 1);
                        $.ajax({
                            type: "post",
                            url: 'file/deleteFile?fileId=' + fileId,
                            success: function (data) {
                                $.messager.alert('消息', data);
                            },
                            error: function (XMLHttpRequest, textStatus,
                                errorThrown) {
                                $.messager.alert('消息', errorThrown);
                            }
                        });
                    }
                });
            }

            /**
             * 取得该条数据所属的文件列表
             * @param row
             */
            function getFileList(row) {
                $.ajax({
                    type: "post",
                    url: "file/getFileList",
                    data: {
                        fileTable: "purchase_order_change",
                        fileRow: row.ordId
                    },
                    success: function (data) {
                        const dataArray = eval(data);
                        initFile(dataArray, row.status);
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        $.messager.alert('消息', errorThrown);
                    }
                });
            }

            /**
             * 初始化该条数据的文件列表
             * @param dataArray
             */
            function initFile(dataArray, status) {
                $("#checkfileList").empty();
                // 			sselectedFileNameList = [];
                selectedFileList = [];
                dataArray
                    .forEach(function (e, i, a) {
                        $("#checkfileList")
                            .append(
                                "<li class=\"fileinfo\">"
                                + "<a style=\" color: blue; margin-left: 30px;\" href=\"javascript:void(0)\" onclick=\"downloadFile('" + e.FILE_NAME + "','"
                                + e.FILE_ID
                                + "')\">"
                                + e.FILE_NAME
                                + "</a>"
                                + (status > 0 ? '' : "<a style=\"display: none; color: red; margin-left: 30px;\" href=\"javascript:void(0)\" onclick=\"RemoveFile(this,'"
                                    + e.FILE_ID + "')\">删除</a>")
                                + "</li>");
                        // 						sselectedFileNameList.push(e.FILE_NAME);
                        if (status > 0) {
                        } else {
                            AddMoushover();
                        }
                    });
            }

            function downloadFile(fileName, fileRow) {
                let url = 'api/file/download?id=' + fileRow
                let xhr = new XMLHttpRequest()
                xhr.open('GET', url, true)
                xhr.setRequestHeader('token', localStorage.getItem('token'));
                xhr.setRequestHeader('userType', localStorage.getItem('userType'));
                xhr.responseType = 'blob'
                xhr.onload = function (data) {
                    if (this.status == 200) {
                        let blob = this.response
                        let reader = new FileReader()
                        reader.readAsDataURL(blob)
                        reader.onload = function (e) {
                            let a = document.createElement('a')
                            a.download = fileName
                            a.href = e.target.result
                            $('body').append(a)
                            a.click()
                            $(a).remove()
                        }
                    } else {

                    }
                }
                xhr.send()
            }
        </script>

        </html>